#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户数据模型
"""

from database import db
from datetime import datetime

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(100), unique=True, nullable=False, comment='微信OpenID')
    unionid = db.Column(db.String(100), unique=True, nullable=True, comment='微信UnionID')
    nickname = db.Column(db.String(100), nullable=True, comment='用户昵称')
    avatar_url = db.Column(db.String(500), nullable=True, comment='头像地址')
    phone = db.Column(db.String(20), nullable=True, comment='手机号码')
    gender = db.Column(db.Integer, default=0, comment='性别：0未知，1男，2女')
    city = db.Column(db.String(50), nullable=True, comment='城市')
    province = db.Column(db.String(50), nullable=True, comment='省份')
    country = db.Column(db.String(50), nullable=True, comment='国家')
    
    # 会员信息
    is_member = db.Column(db.Boolean, default=False, comment='是否会员')
    member_level = db.Column(db.String(20), default='普通', comment='会员等级')
    member_expire_date = db.Column(db.DateTime, nullable=True, comment='会员到期时间')
    
    # 账户信息
    balance = db.Column(db.DECIMAL(10, 2), default=0.00, comment='账户余额')
    total_recharge = db.Column(db.DECIMAL(10, 2), default=0.00, comment='累计充值')
    total_consumption = db.Column(db.DECIMAL(10, 2), default=0.00, comment='累计消费')
    
    # 系统字段
    status = db.Column(db.Integer, default=1, comment='状态：1正常，0禁用')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    last_login_at = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    
    # 关联关系
    orders = db.relationship('Order', backref='user', lazy='dynamic')
    recharges = db.relationship('Recharge', backref='user', lazy='dynamic')
    
    def to_dict(self):
        return {
            'id': self.id,
            'openid': self.openid,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'phone': self.phone,
            'gender': self.gender,
            'city': self.city,
            'province': self.province,
            'country': self.country,
            'is_member': self.is_member,
            'member_level': self.member_level,
            'member_expire_date': self.member_expire_date.isoformat() if self.member_expire_date else None,
            'balance': float(self.balance),
            'total_recharge': float(self.total_recharge),
            'total_consumption': float(self.total_consumption),
            'status': self.status,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None
        }
    
    def __repr__(self):
        return f'<User {self.nickname or self.openid}>'